﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MapInfo.MiPro.Interop;
using System.IO;

namespace CustomMapinfoWindows.ViewModels
{
    public class WorkSpaceViewModel : MapinfoFileViewModel
    {
        public WorkSpaceViewModel(string filePath, TreeViewItemViewModel parent)
            : base(filePath, parent, true, false)
        { }

        public override void OpenFile()
        {
            InteropServices.MapInfoApplication.Do("Run Application \"" + this.FullPath + "\"");
        }

        /// <summary>
        /// Reads the header of the workspace to find the tables that are opened by the workspace and 
        /// loads them as children for the workspace.
        /// </summary>
        protected override void LoadChildren()
        {
            string line;
            using (StreamReader reader = new StreamReader(this.FullPath))
            {
                line = reader.ReadLine();
                while (!line.Contains("Map From"))
                {
                    if (line.Contains("Open Table"))
                    {
                        string path = line.Substring(line.IndexOf('"') + 1, line.LastIndexOf('"') - line.IndexOf('"') - 1);
                        path = path + ".Tab";

                        if (!Path.IsPathRooted(path))
                        {
                            path = Path.Combine(Path.GetDirectoryName(this.FullPath), path);
                        }
                        TabFileViewModel tabfile = new TabFileViewModel(path, this, true);
                        base.Children.Add(tabfile);
                    }
                    line = reader.ReadLine();
                }
            }
        }

        public List<MenuItem> MenuOptions
        {
            get
            {
                var menu = new List<MenuItem>();
                menu.Add(new MenuItem("Edit") { Command = new DelegateCommand(EditWorkspace) });
                return menu;
            }
        }

        public void EditWorkspace()
        {
            string editor = Globals.DefaultTextEditor;
            System.Diagnostics.Process.Start(editor, this.FullPath);
            base.IsExpanded = false;
            base.IsDirty = true;
        }
    }
}
